package net.ck.hzq;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.msd.ocr.idcard.LibraryInitOCR;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import Bean.AuthBean;
import Bean.AuthParamBean;
import Utils.FileUtil;
import Utils.HelloWordModel;
import Utils.OCRUtils;
import Utils.ScreenUtil;
import Utils.SharedPrefStore;
import Utils.SystemDatas;
import Utils.ToastUtil;
import activity.glide.GlideApp;
import base.BaseActivity;
import event.LoginEvent;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import util.PermissionUtils;
import widget.CitySelectView;

import static Utils.FileUtil.compress;

public class SmActivity extends BaseActivity implements View.OnClickListener {

    private CitySelectView citySelectView;

    private TextView addressTv;
    private String mAddressCode;

    private String card[];
    private String cardNum, cardType, cardBank, cardVerificationCode;

    private static final int REQUEST_CAMERA_CODE = 10, REQUEST_PREVIEW_CODE = 20;

    private Bitmap bitmap;

    private final ArrayList<String> imagePaths_enbo = new ArrayList<String>();

    private static PermissionListener mListener;

    public static final int TAKE_PHOTO = 1, CHOOSE_PHOTO = 2, CROP_PHOTO = 3;

    private File cacheFile, cameraFile;

    private LinearLayout sm_linear1, sm_linear2;

    private ImageView idFrontIv, idBackIv, holdIv, bankCardIv;

//    private boolean hasGotToken = false;

    private boolean sfzzm = false, sfzfm = false, zp = false, yhk = false;
    private int step = 1;//步骤状态 1 扫描身份证正面 2身份证反面 3确认身份证信息　４自拍 ５银行卡 ６填写所有信息

    private String cachPath, sfzname = "", sfzxb = "", sfzid = "", sfzqx = "", sfzdz = "";//图片路径，身份证名字，身份证性别，身份证号，身份证期限,身份证地址
    private String filepathsfzzm = "", filepathsfzfm = "", filepathzp = "", filepathyhk = "";//身份证正面路径，身份证反面路径，自拍路径，银行卡路径

    private ImageView sm_back, sm_title_img1, sm_title_img2, sm_title_img3, sm_title_img4, sm_img;//第一个　顶部　当前步骤　
    private TextView sm_title_txt1, sm_title_txt2, sm_title_txt3, sm_title_txt4;//第一个　顶部　当前步骤　
    private View sm_title_vw1, sm_title_vw2, sm_title_vw3;//第一个　顶部　当前步骤　
    private AppCompatEditText sm_linear1_txt1, sm_linear1_txt2, sm_linear1_txt3, sm_linear1_txt4;
    private TextView sm_linear2_txt1, sm_linear2_txt2, sm_txt_ts;//Linear ２ 里的内容
    private AppCompatEditText sm_linear2_txt3, sm_linear2_txt4;
    private AppCompatEditText openAccountBankEt;

    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;
    private static final int REQUEST_CODE_FACE = 203;
    private static final int REQUEST_CODE_CAMERA = 102;
    private static final int REQUEST_CODE_BANKCARD = 111;
    //申请权限
    private final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,

    };
    private final int REQUEST_WRITE = 2;
    private Button sm_but_sfzzm;

    private String base64_sfzzm = "", base64_sfzfm = "", base64_zp = "", base64_yhk = "";

//    private boolean checkGalleryPermission() {
//        int ret = ActivityCompat.checkSelfPermission(SmActivity.this, android.Manifest.permission
//                .READ_EXTERNAL_STORAGE);
//        if (ret != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(SmActivity.this,
//                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
//                    1000);
//            return false;
//        }
//        return true;
//    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_sm;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        } else {
            requestMorePermissions();
        }
        //  初始化本地质量控制模型,释放代码在onDestory中
        //  调用身份证扫描必须加上 intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true); 关闭自动初始化和释放本地模型
        /**
         * 自定义license的文件路径和文件名称，以license文件方式初始化
         */
//        OCR.getInstance(getApplicationContext()).initAccessToken(new OnResultListener<AccessToken>() {
//            @Override
//            public void onResult(AccessToken accessToken) {
//                String token = accessToken.getAccessToken();
////                    hasGotToken = true;
//            }
//
//            @Override
//            public void onError(OCRError error) {
//                error.printStackTrace();
////                    alertText("自定义文件路径licence方式获取token失败", error.getMessage());
//            }
//        }, "aip-ocr.license", getApplicationContext());
        TobuyApplication.getmInstance().onActivityCreate(this);
        sm_title_img1 = findViewById(R.id.sm_title_img1);
        sm_title_img2 = findViewById(R.id.sm_title_img2);
        sm_title_img3 = findViewById(R.id.sm_title_img3);
        sm_title_img4 = findViewById(R.id.sm_title_img4);
        sm_title_txt1 = findViewById(R.id.sm_title_txt1);
        sm_title_txt2 = findViewById(R.id.sm_title_txt2);
        sm_title_txt3 = findViewById(R.id.sm_title_txt3);
        sm_title_txt4 = findViewById(R.id.sm_title_txt4);
        sm_title_vw1 = findViewById(R.id.sm_title_vw1);
        sm_title_vw2 = findViewById(R.id.sm_title_vw2);
        sm_title_vw3 = findViewById(R.id.sm_title_vw3);
        sm_linear1_txt1 = findViewById(R.id.sm_linear1_txt1);
        sm_linear1_txt2 = findViewById(R.id.sm_linear1_txt2);
        sm_linear1_txt3 = findViewById(R.id.sm_linear1_txt3);
        sm_linear1_txt4 = findViewById(R.id.sm_linear1_txt4);
        sm_linear2_txt1 = findViewById(R.id.sm_linear2_txt1);
        sm_linear2_txt2 = findViewById(R.id.sm_linear2_txt2);
        sm_linear2_txt3 = findViewById(R.id.sm_linear2_txt3);
        sm_linear2_txt4 = findViewById(R.id.sm_linear2_txt4);
        openAccountBankEt = findViewById(R.id.et_open_account_bank);
        sm_txt_ts = findViewById(R.id.sm_txt_ts);
        addressTv = findViewById(R.id.address_input);
        sm_linear1 = findViewById(R.id.sm_linear1);
        sm_linear2 = findViewById(R.id.sm_linear2);
        sm_img = findViewById(R.id.sm_img);
        sm_but_sfzzm = findViewById(R.id.sm_but_sfzzm);
        sm_back = findViewById(R.id.sm_back);
        sm_but_sfzzm.setOnClickListener(this);
        sm_back.setOnClickListener(this);

        idFrontIv = findViewById(R.id.image_id_card_front);
        idBackIv = findViewById(R.id.image_id_card_back);
        holdIv = findViewById(R.id.image_hold);
        bankCardIv = findViewById(R.id.image_bank_card);

        cachPath = getDiskCacheDir(this) + "/crop_image.jpg";
        cacheFile = getCacheFile(new File(getDiskCacheDir(this)), "crop_image.jpg");

        // 地址选择
        findViewById(R.id.address_layout).setOnClickListener(this);
        citySelectView = findViewById(R.id.city_select_view);
        citySelectView.setAddressSelectedListener((code, address) -> {
            mAddressCode = code;
            citySelectView.setVisibility(View.GONE);
            addressTv.setText(address);
            addressTv.setTextColor(getResources().getColor(R.color.tc_666666));
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sm_back:
                finish();
                break;
            case R.id.sm_but_sfzzm:
                if (step == 1) {
//                    OCRUtils.startIDCardFront(this, REQUEST_CODE_PICK_IMAGE_FRONT);
                    //跳转至身份证识别页面
//                    Intent intent = new Intent(SmActivity.this, CameraActivity.class);
//                    intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
//                            FileUtil.getSaveFileSfzzm(getApplication()).getAbsolutePath());
//                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
//                    startActivityForResult(intent, REQUEST_CODE_CAMERA);

                    //身份证识别初始化
                    LibraryInitOCR.initOCR(this);
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("saveImage", true);
                    bundle.putInt("requestCode", REQUEST_CODE_PICK_IMAGE_FRONT);
                    bundle.putInt("type", 0); //0身份证, 1驾驶证
                    LibraryInitOCR.startScan(this, bundle);
                } else if (step == 2) {
                    LibraryInitOCR.initOCR(this);
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("saveImage", true);
                    bundle.putInt("requestCode", REQUEST_CODE_PICK_IMAGE_BACK);
                    bundle.putInt("type", 0); //0身份证, 1驾驶证
                    LibraryInitOCR.startScan(this, bundle);
                } else if (step == 3) {

                    sendAuthRequest();
//                    if (TextUtils.isEmpty(sm_linear1_txt1.getText())
//                            || TextUtils.isEmpty(sm_linear1_txt2.getText())
//                            || TextUtils.isEmpty(sm_linear1_txt3.getText())
//                            || TextUtils.isEmpty(sm_linear1_txt4.getText())) {
//                        Toast.makeText(SmActivity.this, "请输入身份证信息", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//                    sm_txt_ts.setText("请正对手机，确保光线充足，并确保是本人操作。");
//                    sm_but_sfzzm.setText("开始自拍");
//                    sm_img.setImageResource(R.drawable.rlsb);
//                    sm_img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
//                    sm_linear1.setVisibility(View.GONE);
//                    sm_title_img1.setImageResource(R.drawable.rzwc);
//                    sm_title_img2.setImageResource(R.drawable.rzz);
//                    sm_title_txt2.setTextColor(getResources().getColor(R.color.colorBlue));
//                    sm_title_vw1.setBackgroundColor(getResources().getColor(R.color.colorBlue));
//                    step = 4;
                } else if (step == 4) {
                    OCRUtils.startFace(this, REQUEST_CODE_FACE);
                } else if (step == 5) {
                    OCRUtils.startBankCard(this, REQUEST_CODE_BANKCARD);
                } else if (step == 6) {
                    if (TextUtils.isEmpty(openAccountBankEt.getText())) {
                        Toast.makeText(SmActivity.this, "请输入结算开户银行!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(sm_linear2_txt3.getText())) {
                        Toast.makeText(SmActivity.this, "请输入银行卡号!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(mAddressCode)) {
                        Toast.makeText(SmActivity.this, "请选择地区!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    sendAuthRequest();
                }
                break;
            case R.id.address_layout:
                ScreenUtil.hideSoftInput(addressTv);
                citySelectView.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 发送实名认证请求
     */
    private void sendAuthRequest() {
        showProgressDialog();
        SharedPrefStore store = new SharedPrefStore();
        AuthParamBean param = new AuthParamBean();
        param.customId = store.getString("id", "0");
        param.idCardNumber = sm_linear1_txt3.getText().toString();
        param.name = sm_linear1_txt1.getText().toString();
        param.region = sfzdz;
//        param.bankno = sm_linear2_txt3.getText().toString();
//        param.bank = cardBank;
//        param.bankadd = addressTv.getText().toString();
//        param.khzh = openAccountBankEt.getText().toString();
        param.idCardFrontImgData = base64_sfzzm;
        param.idCardBackImgData = base64_sfzfm;
//        param.bankFrontImgData = base64_yhk;
//        param.bankBackImgData = base64_zp;
//        param.headimgData = base64_zp;

        Call<AuthBean> userMsgCall = HelloWordModel.getInstance(SmActivity.this).auth(SystemDatas.GetService_URL("auth"), param);
        userMsgCall.enqueue(new Callback<AuthBean>() {
            @Override
            public void onResponse(@NonNull Call<AuthBean> call, @NonNull Response<AuthBean> response) {
                dismissProgressDialog();
                try {
                    if (response.body() != null && "401".equals(response.body().result)) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else if (response.body() != null) {
                        if ("success".equals(response.body().msg)) {
                            ToastUtil.show(SmActivity.this, "提交成功");
                            finish();
                        } else {
                            showFailureTipDialog(response.body().msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<AuthBean> call, @NonNull Throwable t) {
                dismissProgressDialog();
                ToastUtil.show(SmActivity.this, "提交失败");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Log.e("baidu","拍照回调"+data.getData());
        // 身份证正面
//        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
//            String filePath = FileUtil.getSaveFileSfzzm(getApplicationContext()).getAbsolutePath();
//            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
//        }
//        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK) {
//            String filePath = FileUtil.getSaveFileSfzzm(getApplicationContext()).getAbsolutePath();
//            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
//        }

        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK){
            String result = data.getStringExtra("OCRResult");
            try {
                JSONObject jo = new JSONObject(result);
//                StringBuffer sb = new StringBuffer();
//                sb.append(String.format("正面 = %s\n", jo.opt("type")));
//                sb.append(String.format("姓名 = %s\n", jo.opt("name")));
//                sb.append(String.format("性别 = %s\n", jo.opt("sex")));
//                sb.append(String.format("民族 = %s\n", jo.opt("folk")));
//                sb.append(String.format("日期 = %s\n", jo.opt("birt")));
//                sb.append(String.format("号码 = %s\n", jo.opt("num")));
//                sb.append(String.format("住址 = %s\n", jo.opt("addr")));
//                sb.append(String.format("签发机关 = %s\n", jo.opt("issue")));
//                sb.append(String.format("有效期限 = %s\n", jo.opt("valid")));
//                sb.append(String.format("整体照片 = %s\n", jo.opt("imgPath")));
//                sb.append(String.format("头像路径 = %s\n", jo.opt("headPath")));
//                mSuccessText.setText(sb.toString());

                sfzdz = String.valueOf(jo.opt("addr"));
                sfzname = String.valueOf(jo.opt("name"));
                sfzxb = String.valueOf(jo.opt("sex"));
                sfzid = String.valueOf(jo.opt("num"));

                if (sfzdz != null && sfzid != null
                        && sfzname != null && sfzxb != null) {
//                    filepathsfzzm = filePath;
//                    sfzdz = result.getAddress().toString();//地址
//                    sfzid = result.getIdNumber().toString();//ID号
//                    sfzname = result.getName().toString();//姓名
//                    sfzxb = result.getGender().toString();//性别

                    filepathsfzzm =  String.valueOf(jo.opt("imgPath"));
                    sm_linear1_txt1.setText(sfzname);
                    sm_linear1_txt2.setText(sfzxb);
                    sm_linear1_txt3.setText(sfzid);
                    sm_linear2_txt1.setText(sfzname);
                    sm_linear2_txt2.setText(sfzid);
                    base64_sfzzm = "data:image/jpg;base64," + compress(filepathsfzzm);
                    step = 2;
                    sm_but_sfzzm.setText("扫描身份证背面");
                    showSuccessTipDialog("扫描成功!请扫描身份证背面");
                } else {
                    showFailureTipDialog("扫描失败，请重新扫描");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        // 身份证反面
        if (requestCode == REQUEST_CODE_PICK_IMAGE_BACK && resultCode == Activity.RESULT_OK) {
            String result = data.getStringExtra("OCRResult");
            try {
                JSONObject jo = new JSONObject(result);
//                StringBuffer sb = new StringBuffer();
//                sb.append(String.format("正面 = %s\n", jo.opt("type")));
//                sb.append(String.format("姓名 = %s\n", jo.opt("name")));
//                sb.append(String.format("性别 = %s\n", jo.opt("sex")));
//                sb.append(String.format("民族 = %s\n", jo.opt("folk")));
//                sb.append(String.format("日期 = %s\n", jo.opt("birt")));
//                sb.append(String.format("号码 = %s\n", jo.opt("num")));
//                sb.append(String.format("住址 = %s\n", jo.opt("addr")));
//                sb.append(String.format("签发机关 = %s\n", jo.opt("issue")));
//                sb.append(String.format("有效期限 = %s\n", jo.opt("valid")));
//                sb.append(String.format("整体照片 = %s\n", jo.opt("imgPath")));
//                sb.append(String.format("头像路径 = %s\n", jo.opt("headPath")));
//                mSuccessText.setText(sb.toString());

                sfzdz = String.valueOf(jo.opt("imgPath"));

                String yxq = String.valueOf(jo.opt("valid"));
                if (sfzdz != null ) {
//                    filepathsfzzm = filePath;
//                    sfzdz = result.getAddress().toString();//地址
//                    sfzid = result.getIdNumber().toString();//ID号
//                    sfzname = result.getName().toString();//姓名
//                    sfzxb = result.getGender().toString();//性别

                    filepathsfzfm =  String.valueOf(jo.opt("imgPath"));
                    sm_txt_ts.setText("");
                    GlideApp.with(SmActivity.this)
                            .load(filepathsfzzm)
                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                            .skipMemoryCache(true) // 不使用内存缓存
                            .transform(new RoundedCorners(ScreenUtil.dip2px(SmActivity.this, 10)))
                            .into(sm_img);
                    sfzqx = yxq;
                    sm_linear1_txt4.setText(sfzqx);
                    base64_sfzfm = "data:image/jpg;base64," + compress(filepathsfzfm);
                    sm_linear1.setVisibility(View.VISIBLE);
                    sm_but_sfzzm.setText("提交");
                    step = 3;
                    showSuccessTipDialog("扫描成功!请扫描身份证背面");
                } else {
                    showFailureTipDialog("扫描失败，请重新扫描");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }



        }
        // 人脸拍摄
        if (requestCode == REQUEST_CODE_FACE && resultCode == Activity.RESULT_OK) {
            handleFaceSuccess();
        }
        // 银行卡
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            reBankCard();
        }
    }

    private void handleFaceSuccess() {
        filepathzp = FileUtil.getSaveFileFace(this).getAbsolutePath();
        base64_zp = "data:image/jpg;base64," + compress(filepathzp);
        sm_img.setImageResource(R.drawable.bank);
        sm_img.setScaleType(ImageView.ScaleType.FIT_XY);
        sm_but_sfzzm.setText("扫描结算银行卡");
        sm_title_img2.setImageResource(R.drawable.rzwc);
        sm_title_img3.setImageResource(R.drawable.rzz);
        sm_title_txt3.setTextColor(getResources().getColor(R.color.colorBlue));
        sm_title_vw2.setBackgroundColor(getResources().getColor(R.color.colorBlue));
        step = 5;
        Toast.makeText(SmActivity.this, "自拍成功!请扫描银行卡", Toast.LENGTH_SHORT).show();
    }

    private void reBankCard() {
    }

    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public static String imageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            is.close();
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            if (null != is) {
//                try {
//                    is.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }

        }
        return result;
    }

    public class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 7) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(SmActivity.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.item_image, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final String path = listUrls.get(position);
            if (path.equals("000000")) {
                holder.image.setImageResource(R.drawable.submsg_camerac);
            } else {
                GlideApp.with(SmActivity.this)
                        .load(path)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .placeholder(R.drawable.logo)
                        .error(R.drawable.logo)
                        .centerCrop()
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    private File getCacheFile(File parent, String child) {
        File file = new File(parent, child);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = uriToPath(uri);
        startPhotoZoom(new File(imagePath), 350);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private String uriToPath(Uri uri) {
        String path = null;
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf
                        (docId));
                path = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            path = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            path = uri.getPath();
        }
        return path;
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        startPhotoZoom(new File(imagePath), 350);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void startPhotoZoom(File file, int size) {
        Log.i("TAG", getImageContentUri(this, file) + "裁剪照片的真实地址");
        try {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(getImageContentUri(this, file), "image/*");//自己使用Content Uri替换File Uri
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 180);
            intent.putExtra("outputY", 180);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", false);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cacheFile));//定义输出的File Uri
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true);
            startActivityForResult(intent, CROP_PHOTO);
        } catch (ActivityNotFoundException e) {
            String errorMessage = "Your device doesn't support the crop action!";
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public void requestRuntimePermission(String[] permissions, PermissionListener listener) {
        mListener = listener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(SmActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }
        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(SmActivity.this, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            mListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedPermissions.add(permission);
                        }
                    }
                    if (deniedPermissions.isEmpty()) {
                        mListener.onGranted();
                    } else {
                        mListener.onDenied(deniedPermissions);
                    }
                }
                break;
            case REQUEST_WRITE:
                PermissionUtils.onRequestMorePermissionsResult(SmActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {

                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        Toast.makeText(SmActivity.this, "我们需要获取拍照等权限", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        Toast.makeText(SmActivity.this, "我们需要获取拍照等权限", Toast.LENGTH_SHORT).show();
                        showToAppSettingDialog();
                    }
                });
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (citySelectView.getVisibility() == View.VISIBLE) {
            citySelectView.setVisibility(View.GONE);
            return;
        }
        super.onBackPressed();
    }

    public interface PermissionListener {
        void onGranted();

        void onDenied(List<String> deniedPermission);
    }



    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    // 自定义申请多个权限
    private void requestMorePermissions() {
        PermissionUtils.checkMorePermissions(SmActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {

            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                showExplainDialog(permission, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.requestMorePermissions(SmActivity.this, PERMISSIONS, REQUEST_WRITE);
                    }
                });
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(SmActivity.this, PERMISSIONS, REQUEST_WRITE);
            }
        });
    }


    /**
     * 解释权限的dialog
     */
    private void showExplainDialog(String[] permission, DialogInterface.OnClickListener onClickListener) {
        new AlertDialog.Builder(SmActivity.this)
                .setTitle("申请权限")
                .setMessage("我们需要" + Arrays.toString(permission) + "权限")
                .setPositiveButton("确定", onClickListener)
                .show();
    }

    /**
     * 显示前往应用设置Dialog
     */
    private void showToAppSettingDialog() {
        new AlertDialog.Builder(SmActivity.this)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.toAppSetting(SmActivity.this);
                    }
                })
                .setNegativeButton("取消", null).show();
    }

}
